"""
API场景组合测试工具 - 变量处理工具
"""
import re
import json

def process_variables(text, context):
    """处理字符串中的变量占位符"""
    if not text:
        return text
    
    # 匹配 ${xxx} 格式的变量
    pattern = r'\${([^}]+)}'
    
    def replace_var(match):
        var_name = match.group(1)
        
        # 处理复杂表达式，如 ${response.data.id}
        if '.' in var_name:
            parts = var_name.split('.')
            current = context
            
            for part in parts:
                # 处理数组索引，如 items[0]
                array_match = re.match(r'(.+)\[(\d+)\]', part)
                if array_match:
                    array_name = array_match.group(1)
                    array_index = int(array_match.group(2))
                    
                    if array_name in current and isinstance(current[array_name], list) and len(current[array_name]) > array_index:
                        current = current[array_name][array_index]
                    else:
                        return match.group(0)  # 保持原样
                else:
                    if isinstance(current, dict) and part in current:
                        current = current[part]
                    else:
                        return match.group(0)  # 保持原样
            
            # 将对象转换为字符串
            if isinstance(current, (dict, list)):
                return json.dumps(current, ensure_ascii=False)
            else:
                return str(current)
        else:
            # 简单变量
            if var_name in context.get('variables', {}):
                value = context['variables'][var_name]
                
                # 将对象转换为字符串
                if isinstance(value, (dict, list)):
                    return json.dumps(value, ensure_ascii=False)
                else:
                    return str(value)
            else:
                return match.group(0)  # 保持原样
    
    # 替换所有变量
    return re.sub(pattern, replace_var, text)